/*******************************************************************************
 * Copyright 2007, 2009 InnovaSoft SA http://www.innovasoft.biz/
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *       http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *******************************************************************************/
package biz.innovasoft.nodb.impl;

import java.io.Serializable;
import java.util.Collection;
import java.util.Map;

import biz.innovasoft.nodb.Repository;
import biz.innovasoft.nodb.RepositoryException;
import biz.innovasoft.nodb.ValidationException;
import biz.innovasoft.nodb.UpdateValidator;
import biz.innovasoft.nodb.query.Tuple;

/**
 * 
 * @author Diego Miranda
 *
 */
public class UpdateHelper implements Serializable {

	private static final long serialVersionUID = -4757833261740986873L;

	private GenericRepository repository;
	
	public UpdateHelper (GenericRepository repository) {
		this.repository = repository;
	}
	
	public Object update (Long oid, Object object) throws RepositoryException {
		return update (oid, object, Repository.INDEX_YES);
	}
	
	public Object update(Long oid, Object object, int index)
			throws RepositoryException {
		if (!repository.getObjects().containsKey(oid)) {
			throw new RepositoryException(
					"Trying to update an object with an inexistent key. OID: "
							+ oid);
		}
		Object old = repository.getByOId(oid);
		validate (oid, old, object); // Check if the object could be updated.
		repository.getObjects().put(oid, object);
		repository.getIndexHelper().reindexObject (oid, object, index);
		return old;
	}

	public void update (Collection<Tuple> tuples, int index) throws RepositoryException {
		for (Tuple tuple : tuples ) {
			update (tuple.oid, tuple.value, index);
		}
	}
	
	private void validate (Long oid, Object oldObj, Object newObj) {
		Map<String,UpdateValidator> validators = repository.getUpdateValidator(oldObj.getClass());
		if ( validators == null ) {
			return;
		}
		for (String key : validators.keySet()) {
			UpdateValidator validator = validators.get(key);
			if (!validator.canUpdate(oldObj, newObj)) {
				throw new ValidationException ("Object with oid: " + oid + 
						" could not be updated. Validator: " + key + " has failed.", oid, key);
			}
		}
	}
	
}
